package com.glowdayz.glowmee.bc;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.glowdayz.common.CookieBox;
import com.glowdayz.common.DBHandler;
import com.glowdayz.glowmee.cmd.RegisterCMD;
import com.glowdayz.glowmee.dao.RegisterDAO;

public class IndexBC extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
       
    public IndexBC() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dpr = request.getRequestDispatcher("/index.jsp");
		dpr.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DBHandler.getInstance().connect();
		
		request.setCharacterEncoding("utf-8");
		
		String admin_id = request.getParameter("admin_id");
		String admin_pw = request.getParameter("admin_pw");
		
		String save_id = request.getParameter("save_id");
		if (save_id == null) {
			CookieBox cbox = new CookieBox(request, response);
			cbox.addCookie("save_id", "", 0);
		} else {
			CookieBox cbox = new CookieBox(request, response);
			cbox.addCookie("save_id", admin_id, 60 * 60 * 24);
		}
		
		
		try {
			RegisterCMD item = RegisterDAO.getInstance().doLogin(admin_id, admin_pw);
			
			if (item == null) {
				response.setContentType("text/html; charset=utf-8");
				PrintWriter out = response.getWriter();
				out.print("<script type='text/javascript'>alert('로그인 정보가 올바르지 않습니다.');history.back();</script>");
				return;
			}
			
			HttpSession session = request.getSession();
			session.setMaxInactiveInterval(60 * 120);
			session.setAttribute("ADMIN_INFO", item);
		} catch (SQLException e) {
			DBHandler.getInstance().disconnect();
			e.printStackTrace();
		}
		
		DBHandler.getInstance().disconnect();
		RequestDispatcher dpr = request.getRequestDispatcher("/index.jsp");
		dpr.forward(request, response);
	}

}